//
//  YCLStatusPictureView.swift
//  新浪微博01
//
//  Created by yaochunlin on 16/4/15.
//  Copyright © 2016年 yaochunlin. All rights reserved.
//

import UIKit

import SDWebImage
// collectionViewcell的间距
private let YCLStatusPictureViewCellMargin: CGFloat = 4

// cell的最大列数为3列,列数使用整数
private let YCLStatusPictureViewMaxColumn = 3

//cell的宽高
private let YCLStatusPictureViewItemWH = (UIScreen.mainScreen().bounds.size.width - 2 * YCLStatusCellMargin - (CGFloat(YCLStatusPictureViewMaxColumn) - 1) * YCLStatusPictureViewCellMargin ) / CGFloat(YCLStatusPictureViewMaxColumn)

class YCLStatusPictureView: UICollectionView {
    
    //设置图片url属性
    var pictureURLs: [NSURL]? {
    
        didSet{
        
            //当设置好url后，计算配图的宽高
            let size = calViewSize()
            
            //重新更新约束
            self.snp_updateConstraints { (make) in
                
                make.size.equalTo(size)
            }
            
//            YCLPrint("配图大小\(size)")
            //因为cell的复用重新刷新
            self.reloadData()
            
            
        }
    }
    
    //配图宽高
    private func calViewSize() -> CGSize {
    
        layout.itemSize = CGSize.init(width: YCLStatusPictureViewItemWH, height: YCLStatusPictureViewItemWH)
        layout.minimumLineSpacing = 0
        layout.minimumInteritemSpacing = 0
        
        //判断图片的数量
        let count = pictureURLs?.count ?? 0
        
        if count == 0 {
            
//            YCLPrint("没有图片")
            return CGSizeZero
        }
        
        if count == 1 {
            
            //若图片缓存失败，设置为默认大小
            var size = CGSize.init(width: YCLStatusPictureViewItemWH, height: YCLStatusPictureViewItemWH)
            
            //若缓存成功返回图片原本大小
            let url = pictureURLs?.first
            
            //从缓存中取数据
            if let image = SDImageCache.sharedImageCache().imageFromDiskCacheForKey(url!.absoluteString) {
                
                size = image.size
                
                //将点坐标换位像素
                size = CGSize.init(width: size.width * UIScreen.mainScreen().scale, height: size.height * UIScreen.mainScreen().scale)
                
//                YCLPrint("一张图片的大小:\(size)")
            }
            
            //防止图片太小或太大
            if size.width < 40 {
                size.width = 40
            }
            
            if size.width > UIScreen.mainScreen().bounds.size.width * 0.5 {
                
                size.width =  UIScreen.mainScreen().bounds.size.width  * 0.5
            }
            
            
            layout.itemSize = size
            
            return size
        }
        
        //多张图片确定列数
        layout.minimumInteritemSpacing = YCLStatusPictureViewCellMargin
        layout.minimumLineSpacing = YCLStatusPictureViewCellMargin
        var column = YCLStatusPictureViewMaxColumn
        
        if count == 2 || count == 4 {
            
            column = 2
        }
        
        //确定行数
        let row = (count + column - 1) / column
        
        //确定视图大小
        
        let width = CGFloat(column) * YCLStatusPictureViewItemWH + (CGFloat(column) - 1) * YCLStatusPictureViewCellMargin
        
        let height = CGFloat(row) * YCLStatusPictureViewItemWH + (CGFloat(row) - 1) * YCLStatusPictureViewCellMargin
        
        return CGSize.init(width: width, height: height)

    }

    //设置流布局属性

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var layout = UICollectionViewFlowLayout()
    
    private var Identifier = "Identifier"
    
    //创建YCLStatusPictureView
    init(){
    
        super.init(frame: CGRectZero, collectionViewLayout: layout)
        
        backgroundColor = UIColor.clearColor()
        //设置数据源
        self.dataSource = self
        //注册cell
        self.registerClass(YCLStatusPictureViewCell.self, forCellWithReuseIdentifier: Identifier)
    }
    
}

extension YCLStatusPictureView: UICollectionViewDataSource {

    
    //实现collectionview数据源方法
    public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictureURLs?.count ?? 0
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(Identifier, forIndexPath: indexPath) as! YCLStatusPictureViewCell
        
        cell.imageURL = pictureURLs![indexPath.item]
        
        return cell
        
    }
}

//自定义cell
class YCLStatusPictureViewCell: UICollectionViewCell {
    
    //获得图片url属性
    var imageURL: NSURL? {
    
        didSet {
        
            bgView.sd_setImageWithURL(imageURL)
        }
    }
    

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        //设置ui
        prepareUI()
  
    }
    
    private func prepareUI() {
        
        bgView.contentMode = UIViewContentMode.ScaleAspectFill
        bgView.clipsToBounds = true
    
        contentView.addSubview(bgView)
        
        //设置约束
        bgView.snp_makeConstraints { (make) in
            
            make.edges.equalTo(contentView)
        }
    }
    
    //懒加载控件
    private lazy var bgView:UIImageView = UIImageView()
}
